/*
    Created by IntelliJ IDEA.
    @Auther: gaozhe
    @Date: 2020/6/10 下午 10:05
    
*/
package gaozhe.utils;

import org.apache.commons.io.FileUtils;

import javax.swing.filechooser.FileSystemView;
import java.io.File;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;


public class DownloadThreadUtils {

    static String fileFolderName = null;
    static File homeDirectory = FileSystemView.getFileSystemView().getHomeDirectory();





    public static void downloadImgByUrlHashMap(final HashMap<String,String> hashMap){
        //创建文件夹
        fileFolderName = hashMap.get("fileFolderName");
        String path = homeDirectory.getPath();
        final String pathAndName = path + fileFolderName;
        File newFolder = new File(pathAndName);
        if (!newFolder.exists()){
            newFolder.mkdir();
        }
        final int[] i = {1};
        final int[] j = {1};

        try {

            for (final String key:hashMap.keySet()){
                //获取图片链接
                if (key != "fileFolderName"){

                    new Thread(new Runnable() {
                        public void run() {
                            //commons-IO包下载
                            try {
                                System.out.println("开始下载"+key+" : " +hashMap.get(key));

                                final URL url = new URL(hashMap.get(key));

                                final File destinationFile = new File(pathAndName + "\\" + (i[0]++) + ".jpg");
                                FileUtils.copyURLToFile(url,destinationFile);
                                System.out.println("--第"+ j[0]+++"张图片已下载完成--");

                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
